<template>
	<div style="height:100vh; display:flex; flex-direction:column;">

		<div style="display:flex; height:100%; width:100%;">
			<!-- 左：树形表格 -->
			<div
				style="flex: 0 0 30%; border-right: 1px solid #eee; padding: 12px; overflow:auto; display:flex; flex-direction:column;">
				<a-card title="树形数据（多选）" size="small" style="flex:1; display:flex; flex-direction:column;">
					<div style="flex:1; overflow:auto;">
						<a-table :columns="columns" :data-source="treeData" :row-key="rowKey" :pagination="false"
							:row-selection="rowSelection" :defaultExpandAllRows="true" />
					</div>
					<a-space style="margin-top: 12px;">
						<a-button type="primary" @click="createNodesFromSelected">从选中项创建节点</a-button>
						<a-button @click="clearSelection">清空选择</a-button>
					</a-space>
				</a-card>
			</div>

			<!-- 中：画布容器 -->
			<div style="flex: 0 0 50%; display:flex; flex-direction:column;">
				<div style="flex:1; display:flex; flex-direction:column;">
					<GraphCanvas ref="graphRef" style="flex:1;" />
				</div>
			</div>

			<!-- 右：操作节点Card，分为上中下三部分 -->
			<div
				style="flex: 0 0 20%; border-left: 1px solid #eee; padding: 12px; overflow:auto; display:flex; flex-direction:column;">
				<a-card title="数据处理" size="small" style="margin-bottom: 12px;">
					<div style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom:20px;">
						<!-- 添加 draggable 属性实现拖拽 -->
						<a-button v-for="op in operations.filter((_, i) => i % 3 === 0)" :key="op.code"
							style="width:calc(50% - 4px)" draggable="true" @dragstart="handleOperationDragStart($event, op)">
							{{ op.label }}
						</a-button>
						<!-- 如果按钮数量不足4个，添加占位按钮 -->
						<template v-for="i in (4 - operations.filter((_, j) => j % 3 === 0).length)" :key="'placeholder1-'+i">
							<a-button style="width:calc(50% - 4px)">处理{{ i }}</a-button>
						</template>
					</div>
				</a-card>

				<a-card title="数据输出" size="small" style="margin-bottom: 12px;">
					<div style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom:20px;">
						<!-- 添加 draggable 属性实现拖拽 -->
						<a-button v-for="op in operations.filter((_, i) => i % 3 === 1)" :key="op.code"
							style="width:calc(50% - 4px)" draggable="true" @dragstart="handleOperationDragStart($event, op)">
							{{ op.label }}
						</a-button>
						<!-- 如果按钮数量不足4个，添加占位按钮 -->
						<template v-for="i in (4 - operations.filter((_, j) => j % 3 === 1).length)" :key="'placeholder2-'+i">
							<a-button style="width:calc(50% - 4px)">输出{{ i }}</a-button>
						</template>
					</div>
				</a-card>

				<a-card title="自定义脚本" size="small">
					<a-space direction="vertical" style="width:100%;">
						<!-- 添加 draggable 属性实现拖拽 -->
						<a-button v-for="op in operations.filter((_, i) => i % 3 === 2)" :key="op.code" block
							draggable="true" @dragstart="handleOperationDragStart($event, op)">
							{{ op.label }}
						</a-button>
						<!-- 如果按钮数量不足4个，添加占位按钮 -->
						<template v-for="i in (4 - operations.filter((_, j) => j % 3 === 2).length - 1)" :key="'placeholder3-'+i">
							<a-button block>脚本{{ i }}</a-button>
						</template>
					</a-space>
				</a-card>
			</div>
		</div>

	</div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import GraphCanvas from './components/GraphCanvas.vue'

type TreeNode = { id: string; name: string; children?: TreeNode[] }

const graphRef = ref<InstanceType<typeof GraphCanvas> | null>(null)

const rowKey = 'id'
const columns = [
	{ title: '名称', dataIndex: 'name', key: 'name', width: 200 },
	{ title: 'ID', dataIndex: 'id', key: 'id', width: 120 }
]

const treeData = ref<TreeNode[]>([
	{
		id: 'root1',
		name: '根节点1',
		children: [
			{ id: 'a1', name: 'A-1' },
			{ id: 'a2', name: 'A-2' }
		]
	},
	{
		id: 'root2',
		name: '根节点2',
		children: [
			{
				id: 'b1',
				name: 'B-1',
				children: [
					{ id: 'b1-1', name: 'B-1-1' },
					{ id: 'b1-2', name: 'B-1-2' }
				]
			}
		]
	}
])

const selectedRowKeys = ref<string[]>([])
const selectedRowsCache = ref<TreeNode[]>([])

// 修复勾选框失效问题，使用 computed 属性
const rowSelection = computed(() => ({
	selectedRowKeys: selectedRowKeys.value,
	onChange: (keys: string[], rows: TreeNode[]) => {
		selectedRowKeys.value = keys
		selectedRowsCache.value = rows
	}
}))

function createNodesFromSelected() {
	graphRef.value?.createNodesFromList(selectedRowsCache.value)
}

function clearSelection() {
	selectedRowKeys.value = []
	selectedRowsCache.value = []
}

const operations = ref([
	{ code: 'send_email', label: '发送邮件', type: '数据处理', params: 'smtp_server=smtp.example.com;port=587', config: '{"auth":true,"encryption":"tls"}' },
	{ code: 'validate_input', label: '验证输入', type: '数据处理', params: 'rules=required|email|max:255', config: '{"strict_mode":false,"allow_empty":true}' },
	{ code: 'save_data', label: '保存数据', type: '数据输出', params: 'table=users;columns=id,name,email', config: '{"batch_size":100,"retry_count":3}' },
	{ code: 'generate_token', label: '生成令牌', type: '数据输出', params: 'algorithm=HS256;expires_in=3600', config: '{"secret":"my_secret_key","issuer":"my_app"}' },
	{ code: 'notify_admin', label: '通知管理员', type: '脚本', params: 'recipients=admin@example.com', config: '{"priority":"high","include_details":true}' },
	{ code: 'data_analysis', label: '数据分析', type: '数据处理', params: 'method=statistical;fields=all', config: '{"output_format":"json","visualization":true}' },
	{ code: 'data_export', label: '数据导出', type: '数据输出', params: 'format=csv;destination=/exports', config: '{"compression":true,"split_files":false}' },
	{ code: 'custom_script', label: '自定义脚本', type: '脚本', params: 'script=custom.js', config: '{"timeout":5000,"sandbox":true}' }
])


// 添加拖拽处理函数
function handleOperationDragStart(event: DragEvent, op: { code: string; label: string; type: string; params: string; config: string }) {
	console.log('开始拖拽操作:', op)
	if (event.dataTransfer) {
		event.dataTransfer.setData('application/operation', JSON.stringify(op))
		event.dataTransfer.effectAllowed = 'copy'
		event.dataTransfer.dropEffect = 'copy'
	}
}
</script>